package userInterface;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

import org.quickconnect.QuickConnect;

import beans.ConnectionBean;
import beans.SessionBean;
import Client.ClientController;
import quickConnect.BCOHashPassword;
import quickConnect.QCCommandMappings;


@SuppressWarnings("serial")
public class MainFrame extends JFrame {

	public static final int MAIN_HEIGHT = 515;
	public static final int MAIN_WIDTH = 800;
	public static MainFrame mainFrame;
	public static Color limitedFonts= new Color(89, 166, 225);
	public boolean checker = false;
	//public static StatusBar status;
	public Image img;
	public Image testImage;
	private ArrayList params = null;
	private ArrayList serverParams = null;
	private ArrayList addUserParams = null;

	private JMenuBar menuBar = new JMenuBar();
	private JMenu file = new JMenu("File");
	private JMenu chat = new JMenu("Chat");
	private JMenu moderation = new JMenu("Moderation");
	private JMenu help = new JMenu("Help");

	// Menu items.
	private JMenuItem menuItemNew     = new JMenuItem("New Chat Session", new ImageIcon(getClass().getResource("newchat.png")));
	private JMenuItem menuItemExit   = new JMenuItem("Exit", new ImageIcon(getClass().getResource("exit.png")));
	private JMenuItem menuItemSave    = new JMenuItem("Save", new ImageIcon(getClass().getResource("save.png")));
	private JMenuItem menuItemLogin  = new JMenuItem("Login", new ImageIcon(getClass().getResource("securelogin.png")));
	private JMenuItem menuItemLogout  = new JMenuItem("Logout", new ImageIcon(getClass().getResource("securelogin.png")));
	private JMenuItem menuItemServer    = new JMenuItem("Configure Server", new ImageIcon(getClass().getResource("configureserver.png")));
	private JMenuItem menuItemChatSession    = new JMenuItem("Join Chat", new ImageIcon(getClass().getResource("joinchat.png")));
	private JMenuItem menuItemLeaveSession = new JMenuItem("Leave Session", new ImageIcon(getClass().getResource("leavesession.png")));
	private JMenuItem menuItemRemove   = new JMenuItem("Remove File", new ImageIcon(getClass().getResource("removefile.png")));
	private JMenuItem menuItemGrant  = new JMenuItem("View Users", new ImageIcon(getClass().getResource("viewusers.png")));
	private JMenuItem menuItemClose    = new JMenuItem("Shutdown Session", new ImageIcon(getClass().getResource("shutdownsession.png")));
	private JMenuItem menuItemAdd    = new JMenuItem("Add User", new ImageIcon(getClass().getResource("adduser.png")));
	private JMenuItem menuItemHelp = new JMenuItem("Help", new ImageIcon(getClass().getResource("help.png")));
	private JMenuItem menuItemMute = new JMenuItem("Mute");

	ClientController controller = new ClientController();
	String newSessionPassword = "";

	JTabbedPane tabs = new JTabbedPane(JTabbedPane.TOP);
	ArrayList<ChatSessionPanel> chatSessions = new ArrayList<ChatSessionPanel>();

	ConnectionBean serverConfigs;
	private JTextField ipInput;
	private JLabel portLabel;
	private JTextField portInput;
	private JPanel container;
	private JPanel userContainer;
	private Image login;

	@SuppressWarnings("unchecked")
	public MainFrame() {
		//status = new StatusBar();
		//img = new ImageIcon(getClass().getResource("32x32.png")).getImage();
		login = new ImageIcon(getClass().getResource("loginbutton.png")).getImage();

		// initialize quick connect
		QCCommandMappings.mapCommands();
		MainFrame.mainFrame = this;

		// initialize server connection and login user on startup
		try{
			serverConfigs = new ConnectionBean();
			if (serverConfigs.getIp().equals("")) {
				connectToServer();
			}
			else {
				serverParams = new ArrayList();
				serverParams.add(serverConfigs.getIp());
				Integer i = Integer.parseInt(serverConfigs.getPort());
				serverParams.add(i);
			}
			controller.setIpAddress((String) serverParams.get(0));
			controller.setPort((Integer) serverParams.get(1));
			menuItemLogin.setEnabled(true);

			userLogin();		

		}catch(Exception e){
			//status.setMessage("User chose to bypass Server/User Credentials");
			//			System.out.println("User chose to bypass Server/User Credentials");
		}

		//Configure Layout
		//		this.setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
		//		this.pack();
		this.setLocationRelativeTo(null);


		//Set Frame Settings
		this.setTitle("Villicus");
		this.setIconImage(img);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Organize Interface
		buildMenu();
		setAll(false);
		setSave(false);
		this.add(tabs);

		//Sets status bar at bottom of frame.
		//status.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLoweredBevelBorder()));
		//getContentPane().add(status, BorderLayout.SOUTH);
		Dimension startupSize = new Dimension(800, 515);
		tabs.setPreferredSize(startupSize);
		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);

		// ***********************************************************************************
		// ********************************** ACTION LISTENERS *******************************
		// ***********************************************************************************

		menuItemNew.addActionListener(  // Creates a new Chat Session
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						String name = JOptionPane.showInputDialog("Enter New Chat Session Name");
						if(name != null || !name.equals("")){
							ArrayList params = new ArrayList();
							HashMap map = new HashMap();
							map.put("sessionName", name);

							int result = JOptionPane.showConfirmDialog(null, "Would you like to set a password?","Password?", JOptionPane.YES_NO_OPTION);
							if(result == JOptionPane.YES_OPTION){
								getPassword();
								if(newSessionPassword != null || !newSessionPassword.equals("")){
									try {
										//MainFrame.status.setMessage("found password:" + newSessionPassword);
										//										System.out.println("found password:" + newSessionPassword);
										map.put("password", BCOHashPassword.SHA1(newSessionPassword));
									} catch (NoSuchAlgorithmException e1) {
										e1.printStackTrace();
									} catch (UnsupportedEncodingException e1) {
										e1.printStackTrace();
									}
								}
							}
							map.put("userName", MainFrame.mainFrame.getController().getCurUser().getUsername());
							params.add(map);
							QuickConnect.handleRequest("createSession", params);
						}
					} // End of actionPerformed method.
				}); // End of menuItemNew action listener.

		menuItemLeaveSession.addActionListener(  // Leaves the current Chat Session
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						ArrayList params = new ArrayList();
						HashMap paramsMap = new HashMap();
						ChatSessionPanel panel = (ChatSessionPanel)tabs.getSelectedComponent();
						String sessionId = panel.getSession().getSessionId();
						paramsMap.put("tabsIndex",tabs.getSelectedIndex());
						paramsMap.put("sessionId",sessionId);
						params.add(paramsMap);
						QuickConnect.handleRequest("leaveSession", params);
						
					} 
				}); 
		menuItemSave.addActionListener(  // Saves current chat dialog to text file
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						FileDialog dialog = new FileDialog(MainFrame.mainFrame, "save", FileDialog.SAVE);
						dialog.setVisible(true);
						if (dialog.getFile() != null) {
							String fileName = dialog.getDirectory() + 
							System.getProperty("file.separator") + dialog.getFile() + ".txt";
							File file = new File(fileName);
							FileOutputStream fileOutputStream;
							try {
								fileOutputStream = new FileOutputStream(file);
								int i = tabs.getSelectedIndex();
								ChatSessionPanel panel = (ChatSessionPanel) tabs.getComponentAt(i);
								String chatText = panel.aMessengerPanel.receiveArea.getText();
								fileOutputStream.write(chatText.getBytes());
								fileOutputStream.flush();
								fileOutputStream.close();
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} 
						}

					} 
				});

		menuItemExit.addActionListener(  //  Closes the application
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						if(getController().getSocket() != null){
							try {
								getController().getSocket().close();
							} catch (IOException e1) {
							}
						}
						System.exit(EXIT_ON_CLOSE);
					} 
				});
		menuItemLogin.addActionListener(  // user login
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						try{
							userLogin();						
							QuickConnect.handleRequest("login", params);
						}catch(Exception e1){

						}


					} 
				});
		menuItemLogout.addActionListener(  // logout current user
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						try {
							checker = true;
							getController().getSocket().close();
							setAll(false);
							tabs.setVisible(false);
							userLogin();
						} catch (IOException e1) {
							
						}
					}
				});
		menuItemServer.addActionListener(  //  Connect to the server
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						try{
							connectToServer();
							controller.setIpAddress((String) serverParams.get(0));
							controller.setPort((Integer) serverParams.get(1));
							menuItemLogin.setEnabled(true);
						}catch(Exception e1){

						}

					}
				});
		menuItemChatSession.addActionListener(  //  Join an existing chat session
				new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						ArrayList params = new ArrayList();
						QuickConnect.handleRequest("sessionList", params);
					}
				});

		menuItemAdd.addActionListener( new ActionListener(){  //  add user
			@Override
			public void actionPerformed(ActionEvent arg0) {

				addUser();
				try{
					String un = (String) addUserParams.get(0);
					String pw = (String) addUserParams.get(1);
					ArrayList al = new ArrayList();
					al.add(MainFrame.mainFrame);
					HashMap map = new HashMap();
					String hashString = null;
					try {
						hashString = BCOHashPassword.SHA1(pw);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchAlgorithmException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					map.put("username", un);
					map.put("password", hashString);
					map.put("role", "USER");
					al.add(map);
					if(!un.trim().equals("") && un != null && !pw.trim().equals("") && pw != null){
						QuickConnect.handleRequest("addUser", al);
					}
				} catch (Exception e){
				}
			}
		});

		menuItemClose.addActionListener(new ActionListener(){  //  close current session
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ArrayList params = new ArrayList();
				HashMap mapFacade = new HashMap();
				mapFacade.put("sessionId", ((ChatSessionPanel)MainFrame.mainFrame.getTabs().getSelectedComponent()).getSession().getSessionId());
				params.add(mapFacade); // index 0
				QuickConnect.handleRequest("closeSession", params);
			}

		});
/*
		menuItemGrant.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				ArrayList params = new ArrayList();
				HashMap mapFacade = new HashMap();
				mapFacade.put("sessionId", ((ChatSessionPanel)MainFrame.mainFrame.getTabs().getSelectedComponent()).getSession().getSessionId());
				params.add(mapFacade);
				QuickConnect.handleRequest("getUsersList", params);
			}
		});
		*/
		menuItemMute.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e){
				ArrayList params = new ArrayList();
				HashMap mapFacade = new HashMap();
				mapFacade.put("sessionId", ((ChatSessionPanel)MainFrame.mainFrame.getTabs().getSelectedComponent()).getSession().getSessionId());
				params.add(mapFacade);
				QuickConnect.handleRequest("muteRoom", params);
			}
		   }
		);


		menuItemHelp.addActionListener(new ActionListener(){  //  Help
			@Override
			public void actionPerformed(ActionEvent arg0) {
				HelpDialog help = new HelpDialog();
			}

		});

		menuItemRemove.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ArrayList params = new ArrayList();
				HashMap mapFacade = new HashMap();
				mapFacade.put("sessionId", ((ChatSessionPanel)MainFrame.mainFrame.getTabs().getSelectedComponent()).getSession().getSessionId());
				int row = ((ChatSessionPanel)MainFrame.mainFrame.getTabs().getSelectedComponent()).getaFilePanel().getTable().getSelectedRow();
				String fileId = (String) ((ChatSessionPanel)MainFrame.mainFrame.getTabs().getSelectedComponent()).getaFilePanel().getTable().getModel().getValueAt(row, 2);
				//MainFrame.status.setMessage("File:" + fileId);
				//				System.out.println("File: " + fileId);
				mapFacade.put("fileId", fileId);
				params.add(mapFacade);
				QuickConnect.handleRequest("removeFile", params);
			}

		});

		// ***********************************************************************************
		// *************************** END OF ACTION LISTENERS *******************************
		// ***********************************************************************************
	}

	private void setIconImage(ImageIcon imageIcon) {
		// TODO Auto-generated method stub

	}

	public void newSession(SessionBean newSession) {

		ChatSessionPanel newPanel = new ChatSessionPanel(newSession)
		{
			protected void paintComponent( Graphics g ) { 
				if ( !isOpaque( ) )
				{
					super.paintComponent( g );
					return;
				}
				Color color1 = new Color(58, 58, 58);
				Color color2 = new Color(96, 96, 96);

				Graphics2D g2d = (Graphics2D)g;
				int w = getWidth( );
				int h = getHeight( );

				// Paint a gradient from top to bottom
				GradientPaint gp = new GradientPaint(
						0, 50, color2,
						0, h, color1 );

				g2d.setPaint( gp );
				g2d.fillRect( 0, 0, w, h );

				setOpaque( false );
				super.paintComponent( g );
				setOpaque( true );
			}
		};
		tabs.addTab(newSession.getSessionName(), newPanel);
		tabs.setSelectedComponent(newPanel);
		chatSessions.add(newPanel);
		this.repaint();
		this.pack();
	}


	private JMenuBar buildMenu()
	{
		// Add menus to the menu bar.
		menuBar.add(file);
		menuBar.add(chat);
		menuBar.add(moderation);
		menuBar.add(help);

		// Set mnemonics for menu selections.
		file.setMnemonic('F');
		chat.setMnemonic('C');
		moderation.setMnemonic('M');
		help.setMnemonic('H');

		// Menu items for file menu.
		file.add(menuItemNew);
		file.add(menuItemSave);
		file.add(menuItemExit);

		// Menu items for chat menu.
		//chat.add(menuItemLogin);
		chat.add(menuItemLogout);
		chat.add(menuItemServer);
		chat.addSeparator();
		chat.add(menuItemNew);
		chat.add(menuItemChatSession);
		chat.addSeparator();
		chat.add(menuItemLeaveSession);

		//moderation.add(menuItemGrant);
		//moderation.addSeparator();
		moderation.add(menuItemRemove);
		//moderation.add(menuItemBan);
		moderation.add(menuItemClose);
		moderation.addSeparator();
		moderation.add(menuItemAdd);
		moderation.addSeparator();
		moderation.add(menuItemMute);
		menuItemAdd.setEnabled(false);

		help.add(menuItemHelp);
		// Set mnemonics for menu item selections for file menu.
		menuItemNew.setMnemonic('N');
		menuItemExit.setMnemonic('X');
		menuItemSave.setMnemonic('S');

		// Set mnemonics for menu item selections for chat menu.
		//menuItemLogin.setMnemonic('L');
		menuItemLogout.setMnemonic('O');
		menuItemServer.setMnemonic('S');
		menuItemChatSession.setMnemonic('C');

		menuItemHelp.setMnemonic('H');
		// Set the menu bar in the frame and return menu bar.
		setJMenuBar(menuBar);

		//set shortcut keys and action listers for them to work
		menuItemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_MASK));
		menuItemExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				System.exit(0);
			}
		});

		// Return JMenuBar
		return menuBar;

	} // End of buildMenu() method.

	public ClientController getController() {
		return controller;
	}

	public void setController(ClientController controller) {
		this.controller = controller;
	}

	public JMenuItem getMenuItemAdd() {
		return menuItemAdd;
	}

	public void setAll(boolean setter) {
		menuItemNew.setEnabled(setter);
		//menuItemSave.setEnabled(setter);
		//menuItemLogin.setEnabled(setter);
		menuItemLogout.setEnabled(setter);
		menuItemChatSession.setEnabled(setter);
		menuItemRemove.setEnabled(setter);
		//menuItemBan.setEnabled(setter);
		//menuItemGrant.setEnabled(setter);
		menuItemMute.setEnabled(setter);
		menuItemClose.setEnabled(setter);
		menuItemLeaveSession.setEnabled(setter);
	}
	
	public void setSave(boolean setter) {
		menuItemSave.setEnabled(setter);
	}
	public void setLogin(boolean setter) {
		menuItemLogin.setEnabled(setter);
	}
	public ArrayList<ChatSessionPanel> getChatSessions() {
		return chatSessions;
	}


	public void connectToServer() {
		serverConfigs = new ConnectionBean();
		final JDialog dialog = new JDialog(this, "Server Configuration");
		container = new JPanel(new GridBagLayout())
		{
			protected void paintComponent( Graphics g ) { 
				if ( !isOpaque( ) )
				{
					super.paintComponent( g );
					return;
				}
				Color color1 = new Color(96, 96, 96);
				Color color2 = new Color(58, 58, 58);

				Graphics2D g2d = (Graphics2D)g;
				int w = getWidth( );
				int h = getHeight( );

				// Paint a gradient from top to bottom
				GradientPaint gp = new GradientPaint(
						0, 100, color2,
						0, h, color1 );

				g2d.setPaint( gp );
				g2d.fillRect( 0, 0, w, h );

				setOpaque( false );
				super.paintComponent( g );
				setOpaque( true );
			}
		};

		GridBagConstraints c = new GridBagConstraints();
		
		
		JLabel ipLabel = new JLabel("Server IP :");				
		c.gridx = 0;
		c.gridy = 0;
		c.anchor = GridBagConstraints.EAST;
		c.insets = new Insets(10, 10, 0, 0);
		container.add(ipLabel, c);
		ipLabel.setFont(new Font("Serif", Font.BOLD, 14));
		ipLabel.setForeground(Color.white);

		ipInput = new JTextField(12);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = 0;
		c.insets = new Insets(10, 10, 0, 0);
		container.add(ipInput, c);

		portLabel = new JLabel("Server Port :");
		c.gridx = 0;
		c.gridy = 1;
		c.anchor = GridBagConstraints.EAST;
		c.insets = new Insets(10, 10, 0, 0);
		container.add(portLabel, c);
		portLabel.setFont(new Font("Serif", Font.BOLD, 14));
		portLabel.setForeground(Color.white);

		portInput = new JTextField(12);
		c.gridx = 1;
		c.gridy = 1;
		c.insets = new Insets(10, 10, 0, 0);
		container.add(portInput, c);

		JButton ok = new JButton("OK"){
			public void paint(Graphics g) {
				if (login != null) {
					g.drawImage(login, 0, 0, getWidth(), getHeight(), this);
					setContentAreaFilled(false);
					setBorder(null);
				} else {
					setOpaque(true);
				}
				super.paint(g);
			}};
			c.fill = GridBagConstraints.NONE;
			c.gridx = 1;       
			c.gridy = 2;
			c.anchor = GridBagConstraints.EAST;
			//		c.insets = new Insets(10, 10, 10, 10);
			c.ipadx = 60;
			c.ipady = 10;
			container.add(ok, c);

			//Set ok button font and color
			ok.setFont(new Font("Serif", Font.BOLD, 12));
			ok.setBackground(new Color(96,96,96));
			ok.setForeground(limitedFonts);


			ipInput.setText(serverConfigs.getIp());
			portInput.setText(serverConfigs.getPort());
			//		container.setBorder(BorderFactory.createTitledBorder(
			//				null, "Server Configuration",
			//				TitledBorder.CENTER,
			//				TitledBorder.ABOVE_TOP));
			//		

			dialog.add(container);

			portInput.addActionListener(new ActionListener()
			{
				@SuppressWarnings("unchecked")
				public void actionPerformed(ActionEvent e)
				{

					serverParams = new ArrayList();

					String serverIP = ipInput.getText();
					String port = portInput.getText();

					if ((serverIP.equals("")) || (port.equals(""))) {
						JOptionPane.showMessageDialog(container, "Please enter valid data");
					}

					else {
						serverConfigs.setIp(serverIP);
						serverConfigs.setPort(port);
						serverConfigs.saveBean();
						Integer portNumber = Integer.parseInt(port);
						serverParams.add(serverIP);
						serverParams.add(portNumber);
						dialog.setVisible(false);
						dialog.dispose();
					}

				}
			});
			ok.addActionListener(new ActionListener()
			{
				@SuppressWarnings("unchecked")
				public void actionPerformed(ActionEvent e)
				{

					serverParams = new ArrayList();

					String serverIP = ipInput.getText();
					String port = portInput.getText();

					if ((serverIP.equals("")) || (port.equals(""))) {
						JOptionPane.showMessageDialog(container, "Please enter valid data");
					}

					else {

						serverConfigs.setIp(serverIP);
						serverConfigs.setPort(port);
						serverConfigs.saveBean();
						Integer portNumber = Integer.parseInt(port);
						serverParams.add(serverIP);
						serverParams.add(portNumber);
						dialog.setVisible(false);
						dialog.dispose();
					}

				}
			});
			((java.awt.Frame)dialog.getOwner()).setIconImage(img);
			dialog.setModal(true);
			dialog.setSize(450, 275);
			dialog.setLocationRelativeTo(MainFrame.mainFrame);
			dialog.setVisible(true);
	}

	public void userLogin() {

		userContainer = new JPanel(){
			protected void paintComponent( Graphics g ) { 
				if ( !isOpaque( ) )
				{
					super.paintComponent( g );
					return;
				}
				Color color1 = new Color(58, 58, 58);
				Color color2 = new Color(96, 96, 96);

				Graphics2D g2d = (Graphics2D)g;
				int w = getWidth( );
				int h = getHeight( );

				// Paint a gradient from top to bottom
				GradientPaint gp = new GradientPaint(
						0, 50, color2,
						0, h, color1 );

				g2d.setPaint( gp );
				g2d.fillRect( 0, 0, w, h );

				setOpaque( false );
				super.paintComponent( g );
				setOpaque( true );
			}
		};
		final JPanel userCred = new JPanel(new GridBagLayout());
		userCred.setOpaque(false);
		
		JPanel imageHolder = new JPanel();
		final JLabel logImage = new JLabel(new ImageIcon(getClass().getResource("128x128.png")));
		imageHolder.add(logImage);
		imageHolder.setOpaque(false);

		GridBagConstraints u = new GridBagConstraints();
		u.anchor = GridBagConstraints.EAST;
		final JLabel uNameLabel = new JLabel("Username :");
		u.gridx = 1;
		u.gridy = 0;
		u.anchor = GridBagConstraints.EAST;
		u.insets = new Insets(10, 0, 0, 0);
		userCred.add(uNameLabel, u);
		uNameLabel.setFont(new Font("Serif", Font.BOLD, 14));
		uNameLabel.setForeground(Color.white);

		final JTextField uNameInput = new JTextField(15);
		u.fill = GridBagConstraints.HORIZONTAL;
		u.gridx = 2;
		u.gridy = 0;
		u.insets = new Insets(10, 10, 0, 0);
		userCred.add(uNameInput, u);

		final JLabel pWordLabel = new JLabel("Password :");
		u.gridx = 1;
		u.gridy = 1;
		u.anchor = GridBagConstraints.EAST;
		u.insets = new Insets(10, 10, 0, 0);
		userCred.add(pWordLabel, u);
		pWordLabel.setFont(new Font("Serif", Font.BOLD, 14));
		pWordLabel.setForeground(Color.white);

		final JPasswordField pWordInput = new JPasswordField(15);
		u.gridx = 2;
		u.gridy = 1;
		u.insets = new Insets(10, 10, 0, 0);
		userCred.add(pWordInput, u);

		JButton ok = new JButton("Login"){
			public void paint(Graphics g) {
				if (login != null) {
					g.drawImage(login, 0, 0, getWidth(), getHeight(), this);
					setContentAreaFilled(false);
					setBorder(null);
				} else {
					setOpaque(true);
				}
				super.paint(g);
			}};
			u.fill = GridBagConstraints.NONE;
			u.gridx = 2;       
			u.gridy = 2;
			
			//		c.insets = new Insets(10, 10, 10, 10);
			u.ipadx = 60;
			u.ipady = 10;
			userCred.add(ok, u);

			//Set ok button font and color
			ok.setFont(new Font("Serif", Font.BOLD, 12));
			ok.setBackground(new Color(96,96,96));
			ok.setForeground(limitedFonts);


			//		userCred.setBorder(BorderFactory.createTitledBorder(
			//		null, "Villicus Login",
			//		TitledBorder.CENTER,
			//		TitledBorder.ABOVE_TOP));
			userContainer.add(imageHolder);
			userContainer.add(userCred);
			add(userContainer);


			pWordInput.addActionListener(new ActionListener()
			{
				@SuppressWarnings("unchecked")
				public void actionPerformed(ActionEvent e)
				{

					params = new ArrayList();
					HashMap paramsMap = new HashMap();
					String uName = uNameInput.getText();
					char[] pWord = pWordInput.getPassword();
					pWordInput.setText("");
					if ((uName.equals("")) || (pWord.length == 0)) {
						JOptionPane.showMessageDialog(null, "Please enter valid credentials");
					}

					else {
						String password = new String(pWord);
						paramsMap.put("username", uName);
						paramsMap.put("password", password);
						paramsMap.put("ip", controller.getIpAddress());
						paramsMap.put("port", controller.getPort());
						params.add(paramsMap);
						QuickConnect.handleRequest("login", params);
						//userContainer.setVisible(false);
						//					dialog.dispose();
					}

				}
			});
			ok.addActionListener(new ActionListener()
			{
				@SuppressWarnings("unchecked")
				public void actionPerformed(ActionEvent e)
				{

					params = new ArrayList();
					HashMap paramsMap = new HashMap();
					String uName = uNameInput.getText();
					char[] pWord = pWordInput.getPassword();
					pWordInput.setText("");
					if ((uName.equals("")) || (pWord.length  == 0)) {
						JOptionPane.showMessageDialog(null, "Please enter valid credentials");
					}

					else {
						String password = new String(pWord);
						paramsMap.put("username", uName);
						paramsMap.put("password", password);
						paramsMap.put("ip", controller.getIpAddress());
						paramsMap.put("port", controller.getPort());
						params.add(paramsMap);
						QuickConnect.handleRequest("login", params);
						//userContainer.setVisible(false);
						//					dialog.dispose();
					}

				}
			});
			//		userCred.setModal(true);
			//				userCred.pack();
			userContainer.setSize(MAIN_WIDTH, MAIN_HEIGHT);
			userContainer.setVisible(true);
	}
	
	public void userContainerSetter(boolean setter) {
		userContainer.setVisible(setter);
	}
	public JTabbedPane getTabs() {
		return tabs;
	}

	public void setTabs(JTabbedPane tabs) {
		this.tabs = tabs;
	}
	public void tabsSetter(boolean setter) {
		this.tabs.setVisible(setter);
	}

	private void addUser() {
	    //testImage = new ImageIcon(getClass().getResource("32x32.png")).getImage();
		final JDialog dialog = new JDialog();
		//((java.awt.Frame)dialog.getOwner()).setIconImage(img);
		//dialog.setIconImage(testImage);
		dialog.setLayout(new FlowLayout());
		final JLabel uNameLabel = new JLabel("Username:");
		final JLabel pWordLabel = new JLabel("Password:");
		final JLabel pWordLabel2 = new JLabel("Re-enter Password:");
		final JTextField uNameInput = new JTextField(15);
		final JPasswordField pWordInput = new JPasswordField(15);
		final JPasswordField pWordInput2 = new JPasswordField(15);
		JButton ok = new JButton("Ok");

		JPanel panel1 = new JPanel(new GridLayout(4, 2, 10, 10));
		panel1.add(uNameLabel);
		panel1.add(uNameInput);
		panel1.add(pWordLabel);
		panel1.add(pWordInput);
		panel1.add(pWordLabel2);
		panel1.add(pWordInput2);
		panel1.add(Box.createGlue());
		panel1.add(ok);

		dialog.add(panel1);

		pWordInput2.addActionListener(new ActionListener()
		{
			@SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent e)
			{

				addUserParams = new ArrayList();

				String uName = uNameInput.getText();
				char[] pWord = pWordInput.getPassword();
				char[] pWord2 = pWordInput2.getPassword();

				if ((uName.equals("")) || (pWord.length == 0) || (pWord2.length == 0)) {
					JOptionPane.showMessageDialog(dialog, "Please enter valid credentials");
				}

				else {
					String password = new String(pWord);
					String password2 = new String(pWord2);
					if (password.equals(password2)) {
						addUserParams.add(uName);
						addUserParams.add(password);
						dialog.setVisible(false);
						dialog.dispose();
					}
					else {
						JOptionPane.showMessageDialog(dialog, "Passwords must match");
					}
				}

			}
		});

		ok.addActionListener(new ActionListener()
		{
			@SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent e)
			{

				addUserParams = new ArrayList();

				String uName = uNameInput.getText();
				char[] pWord = pWordInput.getPassword();
				char[] pWord2 = pWordInput2.getPassword();

				if ((uName.equals("")) || (pWord.length == 0) || (pWord2.length == 0)) {
					JOptionPane.showMessageDialog(dialog, "Please enter valid credentials");
				}

				else {
					String password = new String(pWord);
					String password2 = new String(pWord2);
					if (password.equals(password2)) {
						addUserParams.add(uName);
						addUserParams.add(password);
						dialog.setVisible(false);
						dialog.dispose();
					}
					else {
						JOptionPane.showMessageDialog(dialog, "Passwords must match");
					}
				}

			}
		});
		dialog.setModal(true);
		dialog.pack();
		dialog.setLocationRelativeTo(MainFrame.mainFrame);
		dialog.setVisible(true);
	}

	//	private void configureServerLoginUser() {
	//		ConnectionBean serverConfigs = new ConnectionBean();
	//		final JDialog dialog = new JDialog();
	//
	//		ipInput.setText(serverConfigs.getIp());
	//		portInput.setText(serverConfigs.getPort());
	//
	//		JPanel panel1 = new JPanel(new GridBagLayout());
	//		GridBagConstraints cs = new GridBagConstraints();
	//		
	//		final JLabel ipLabel = new JLabel("Server IP:");
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(ipLabel);
	//		
	//		final JTextField ipInput = new JTextField(10);
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(ipInput);
	//		
	//		final JLabel portLabel = new JLabel("Server Port:");
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(portLabel);
	//		
	//		final JTextField portInput = new JTextField(10);
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(portInput);
	//		
	//		final JLabel uNameLabel = new JLabel("Username:");
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(uNameLabel);
	//		
	//		final JTextField uNameInput = new JTextField(10);
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(uNameInput);
	//		
	//		final JLabel pWordLabel = new JLabel("Password:");
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(pWordLabel);
	//		
	//		final JPasswordField pWordInput = new JPasswordField(10);
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(pWordInput);
	//		
	//		JButton cancel = new JButton("Cancel");
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(cancel);
	//		
	//		JButton login = new JButton("Login");
	//		cs.gridx = 0;
	//		cs.gridy = 0;
	//		cs.insets = new Insets(10, 10, 10, 10);
	//		panel1.add(login);
	//
	//		dialog.add(panel1);
	//
	//		cancel.addActionListener(
	//				new ActionListener() {
	//
	//					@Override
	//					public void actionPerformed(ActionEvent e) {
	//						dialog.setVisible(false);
	//						dialog.dispose();
	//					}
	//				});
	//
	//		login.addActionListener(
	//				new ActionListener() {
	//
	//					@Override
	//					public void actionPerformed(ActionEvent e) {
	//						String serverIP = ipInput.getText();
	//						String serverPort = portInput.getText();
	//						String uName = uNameInput.getText();
	//						char[] pWord = pWordInput.getPassword();
	//						if ((serverIP.equals("")) || (serverPort.equals("")) || (uName.equals("")) || (pWord.length == 0)) {
	//							JOptionPane.showMessageDialog(dialog, "Please enter valid data and credentials");
	//						}
	//
	//						else {
	//							ClientController cont = MainFrame.mainFrame.getController();
	//							int portNumber = Integer.parseInt(serverPort);
	//							cont.setIpAddress(serverIP);
	//							cont.setPort(portNumber);
	//
	//							params = new ArrayList();
	//							HashMap parameters = new HashMap();
	//							parameters.put("username", uName);
	//							parameters.put("password", pWord);
	//							parameters.put("ip", controller.getIpAddress());
	//							parameters.put("port", controller.getPort());
	//							params.add(parameters);
	//							QuickConnect.handleRequest("login", params);
	//						}
	//
	//					}
	//				});
	//
	//		dialog.setModal(true);
	//		dialog.pack();
	//		dialog.setLocationRelativeTo(MainFrame.mainFrame);
	//		dialog.setVisible(true);
	//	}

	public void getPassword(){

		final JDialog dialog = new JDialog(MainFrame.mainFrame, "User Login");

		JPanel panel1 = new JPanel(new GridBagLayout())
		{
			protected void paintComponent( Graphics g ) { 
				if ( !isOpaque( ) )
				{
					super.paintComponent( g );
					return;
				}
				Color color1 = getBackground( );
				Color color2 = color1.darker( );

				Graphics2D g2d = (Graphics2D)g;
				int w = getWidth( );
				int h = getHeight( );

				// Paint a gradient from top to bottom
				GradientPaint gp = new GradientPaint(
						0, 0, color1,
						0, h, color2 );

				g2d.setPaint( gp );
				g2d.fillRect( 0, 0, w, h );

				setOpaque( false );
				super.paintComponent( g );
				setOpaque( true );
			}
		};
		GridBagConstraints pw = new GridBagConstraints();
		//		JPanel panel2 = new JPanel();
		//		JPanel panel3 = new JPanel();

		final JLabel pWordLabel = new JLabel("Password:");		
		pw.gridx = 0;
		pw.gridy = 0;
		pw.insets = new Insets(10, 10, 10, 10);
		panel1.add(pWordLabel, pw);

		final JPasswordField pWordInput = new JPasswordField(15);
		pw.gridx = 1;
		pw.gridy = 0;
		pw.weightx = 1;
		pw.insets = new Insets(10, 10, 10, 10);
		panel1.add(pWordInput, pw);


		JButton ok = new JButton("Ok");
		pw.gridx = 2;
		pw.gridy = 0;
		pw.insets = new Insets(10, 10, 10, 10);
		panel1.add(ok, pw);

		dialog.add(panel1);

		ActionListener go = new ActionListener()
		{
			@SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent e)
			{


				char[] pWord = pWordInput.getPassword();


				newSessionPassword = new String(pWord);
				dialog.setVisible(false);
				dialog.dispose();
			}
		};

		pWordInput.addActionListener(go);
		ok.addActionListener(go);
		dialog.setModal(true);
		dialog.setSize(400, 175);
		dialog.setLocationRelativeTo(MainFrame.mainFrame);
		dialog.setVisible(true);
	}
	
	public void setMuteText(String txt)
	{
		menuItemMute.setText(txt);
	}

	public static void main(String[] args) {
		if ( System.getProperty( "os.name" ).toLowerCase( ).startsWith( "windows" ) )
		{
			try {
				for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
					if ("Nimbus".equals(info.getName())) {
						UIManager.setLookAndFeel(info.getClassName());
						break;
					}
				}
			} catch (Exception e) {
				// If Nimbus is not available, you can set the GUI to another look and feel.
			}
		}

		//***Commented out for development phase**//
//				VillicusSplash splash = new VillicusSplash(4000);
//				splash.showSplash();

		@SuppressWarnings("unused")
		MainFrame mf = new MainFrame();
	}
}







